#!/usr/bin/bash
# by: micro li (lilongen@163.com, microli@sz.webex.com)
# date: 4/13/2010
#

updatedAvailable=0
checkVersion() {
	echo 
	echo "Check whether updated build is available..."
	echo 
	
	localVer=""
	if [ -e VERSION ] 
	then
		localVer=`cat VERSION`
	fi
	
	echo "Current build: $localVer"
	if [ ! -d .update ]
	then
		mkdir .update
	else 
		rm -rf .update/*	
	fi
	
	echo "Check latest build..."
	cvs -Q -d :pserver:anonymous:@cvschangeviewer.cvs.sourceforge.net:/cvsroot/cvschangeviewer co -d .update cvschangeviewer/VERSION
	remoteVer=`cat .update/VERSION`
	
	echo "Latest build: $remoteVer"
	echo 
	
	if [ "$localVer" = ""  ] || [[ "$localVer" < "$remoteVer" ]]
	then
		updatedAvailable=1
	fi
}


update() {
	echo 
	echo "upgrading..."
	echo
	
	cd .update
	
	ccvId="ccv-2.0"
	buildNO=${remoteVer##*.}
	remotePackageName="$ccvId-${buildNO}.tar.gz"
	packageName="$ccvId.tar.gz"
		
	
	latest="http://sourceforge.net/projects/cvschangeviewer/files/$remotePackageName/download"
	
	echo "Download CCV latest build..."
	echo 
	wget $latest
	tar -xzf $remotePackageName
	
	
	echo "Update files..."
	echo 
	tar -xzf $packageName
	rm -rf ccv/config/config.xml
	rm -rf ccv/config/cvs.accounts
	
	rm -rf $packageName
	tar -czf $packageName ccv/
	rm -rf ccv/
	tar -xzf $packageName -C ../../
	
	echo "Update files: finished"
	cd ..
	chmod 755 *
	chmod 777 config/
	chmod 777 config/CFG_PWD
	chmod 777 operate/
	chmod 777 web/reports/
	
	echo 
	echo "Upgrade: done!"
	echo "Now your CCV version is: $remoteVer";
	echo
}


main() {
	checkVersion
	
	if [ $updatedAvailable -eq 1 ]
	then
		update
	else
		echo 
		echo "Your CCV already is the latest package!"
		echo 
	fi
}

main